#include <jni.h>
#include <string>
#include <vector>
#include <sstream>
#include <chrono>
#include <cmath>    // 用于std::abs, std::round, atan2
#include <cstdlib>  // 用于abs函数（兼容C风格）
#include <random>
#include <android/log.h>
#include <android/bitmap.h>

#define TAG "jni-jni"

namespace {
    jobject g_context = nullptr;
    std::string g_deviceId;
    jlong g_buildTime = 0;
    jmethodID g_getSharedPrefsMethod = nullptr;
    jmethodID g_getStringMethod = nullptr;
}

static jclass g_FloatClass = nullptr;
static jmethodID g_FloatInit = nullptr;
static jclass g_PairClass = nullptr;
static jmethodID g_PairInit = nullptr;

struct CDKEncryptedInfo {
    std::string deviceId;
    std::string sessionId;
    long startTimestamp{};
    long expiredTimestamp{};
    std::string cdk;
};

static const char* currentPackageName = nullptr;
static const char* currentSignature = nullptr;
static time_t lastCheckPermissionTime = 0;
static bool lastCheckPermissionResult = false;
static time_t lastCheckCDKeyTime = 0;
static int lastCheckCDKeyResult = 0;

static jboolean isCopy = JNI_FALSE;

static bool checkException(JNIEnv* env, void* obj) {
    if (env->ExceptionCheck()) env->ExceptionClear();
    return obj != nullptr;
}

// MD5计算辅助函数
jstring javaMd5(JNIEnv* env, jbyteArray data) {
    jclass messageDigestClass = env->FindClass("java/security/MessageDigest");
    jobject messageDigest = env->CallStaticObjectMethod(messageDigestClass,
                                                        env->GetStaticMethodID(messageDigestClass, "getInstance", "(Ljava/lang/String;)Ljava/security/MessageDigest;"),
                                                        env->NewStringUTF("MD5"));

    jbyteArray digestByteArray = (jbyteArray)env->CallObjectMethod(messageDigest,
                                                                   env->GetMethodID(messageDigestClass, "digest", "([B)[B"), data);

    if (!checkException(env, digestByteArray)) {
        env->DeleteLocalRef(messageDigest);
        env->DeleteLocalRef(messageDigestClass);
        return nullptr;
    }

    jclass stringBuilderClass = env->FindClass("java/lang/StringBuilder");
    jobject stringBuilder = env->NewObject(stringBuilderClass,
                                           env->GetMethodID(stringBuilderClass, "<init>", "()V"));
    jmethodID appendMethod = env->GetMethodID(stringBuilderClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;");

    jclass integerClass = env->FindClass("java/lang/Integer");
    jmethodID toHexStringMethod = env->GetStaticMethodID(integerClass, "toHexString", "(I)Ljava/lang/String;");

    jint length = env->GetArrayLength(digestByteArray);
    jbyte* temp = env->GetByteArrayElements(digestByteArray, &isCopy);

    for (int i = 0; i < length; ++i) {
        jstring hex = (jstring)env->CallStaticObjectMethod(integerClass, toHexStringMethod, temp[i] & 0xFF);
        if (env->CallIntMethod(hex, env->GetMethodID(env->FindClass("java/lang/String"), "length", "()I")) < 2) {
            env->CallObjectMethod(stringBuilder, appendMethod, env->NewStringUTF("0"));
        }
        env->CallObjectMethod(stringBuilder, appendMethod, hex);
        env->DeleteLocalRef(hex);
    }

    jstring result = (jstring)env->CallObjectMethod(stringBuilder,
                                                    env->GetMethodID(stringBuilderClass, "toString", "()Ljava/lang/String;"));
    result = (jstring)env->CallObjectMethod(result,
                                            env->GetMethodID(env->FindClass("java/lang/String"), "toLowerCase", "()Ljava/lang/String;"));

    // 清理资源
    env->ReleaseByteArrayElements(digestByteArray, temp, JNI_ABORT);
    env->DeleteLocalRef(messageDigest);
    env->DeleteLocalRef(messageDigestClass);
    env->DeleteLocalRef(stringBuilderClass);
    env->DeleteLocalRef(stringBuilder);
    env->DeleteLocalRef(integerClass);

    return result;
}

// 包名获取辅助函数
jstring getPackageName(JNIEnv* env, jobject context) {
    return (jstring)env->CallObjectMethod(context,
                                          env->GetMethodID(env->GetObjectClass(context), "getPackageName", "()Ljava/lang/String;"));
}

// 签名获取辅助函数
jstring getSignature(JNIEnv* env, jobject context) {
    jclass contextClass = env->GetObjectClass(context);
    jobject pm = env->CallObjectMethod(context,
                                       env->GetMethodID(contextClass, "getPackageManager", "()Landroid/content/pm/PackageManager;"));

    jclass pmClass = env->GetObjectClass(pm);
    jstring packageName = getPackageName(env, context);
    jobject packageInfo = env->CallObjectMethod(pm,
                                                env->GetMethodID(pmClass, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;"),
                                                packageName, 64);

    jobjectArray signatures = (jobjectArray)env->GetObjectField(packageInfo,
                                                                env->GetFieldID(env->GetObjectClass(packageInfo), "signatures", "[Landroid/content/pm/Signature;"));
    jobject signature = env->GetObjectArrayElement(signatures, 0);
    jbyteArray signatureBytes = (jbyteArray)env->CallObjectMethod(signature,
                                                                  env->GetMethodID(env->GetObjectClass(signature), "toByteArray", "()[B"));

    jstring result = javaMd5(env, signatureBytes);

    // 清理资源
    env->DeleteLocalRef(signatures);
    env->DeleteLocalRef(signature);
    env->DeleteLocalRef(signatureBytes);
    env->DeleteLocalRef(packageInfo);
    env->DeleteLocalRef(pm);
    env->DeleteLocalRef(pmClass);
    env->DeleteLocalRef(packageName);
    env->DeleteLocalRef(contextClass);

    return result;
}

// 权限验证核心逻辑
bool innerCheckPermission(JNIEnv* env) {
    jclass appClass = env->FindClass("abc/reflect/App");
    if (!checkException(env, appClass)) return false;

    jclass companionClass = env->FindClass("abc/reflect/App$Companion");
    if (!checkException(env, companionClass)) return false;

    jfieldID companionField = env->GetStaticFieldID(appClass, "Companion", "Labc/reflect/App$Companion;");
    if (!checkException(env, companionField)) return false;

    jobject companion = env->GetStaticObjectField(appClass, companionField);
    jobject appInstance = env->CallObjectMethod(companion,
                                                env->GetMethodID(companionClass, "take", "()Labc/reflect/App;"));

    jobject context = env->CallObjectMethod(appInstance,
                                            env->GetMethodID(appClass, "getBaseContext", "()Landroid/content/Context;"));

    // 动态生成签名校验值
    // 90018de5e01abd13daf68f982bdd3f9e
    //    __android_log_print(ANDROID_LOG_INFO, "jni-jni", "currentSignature %s", currentSignature);
    const char* validSignature = "90018de5e01abd13daf68f982bdd3f9e";

    if (!currentPackageName) {
        currentPackageName = env->GetStringUTFChars(getPackageName(env, context), &isCopy);
    }
    if (!currentSignature) {
        currentSignature = env->GetStringUTFChars(getSignature(env, context), &isCopy);
    }

    bool result = (strcmp(currentPackageName, "com.netease.sword.huawei") == 0) &&
                  (strcmp(currentSignature, validSignature) == 0);

    // 清理资源
    env->DeleteLocalRef(companion);
    env->DeleteLocalRef(appInstance);
    env->DeleteLocalRef(context);
    env->DeleteLocalRef(appClass);
    env->DeleteLocalRef(companionClass);

    return result;
}

// 带缓存的权限检查
bool checkPermission(JNIEnv* env) {
    time_t current = time(nullptr);
    if (current - lastCheckPermissionTime < 120) return lastCheckPermissionResult;

    lastCheckPermissionResult = innerCheckPermission(env);
    lastCheckPermissionTime = current;
    return lastCheckPermissionResult;
}

// 颜色相似度判断
bool isSimilarColor(int r1, int g1, int b1, int r2, int g2, int b2, int dr, int dg, int db) {
    return abs(r1 - r2) <= dr &&
           abs(g1 - g2) <= dg &&
           abs(b1 - b2) <= db;
}

// 全局常量
static constexpr const char* rsaPublicKey =
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjsI6HDiqoDGpy32GFsWBTwcI9PiIo+UV\n"
        "qZFzTDjNBX+6M/ItlLpj/axotGSsW0kLEHQkThHS0RgihKlXsdMDqoa3tV2+4rAhNSu7kYGo4eyR\n"
        "RB22CJOsqMcYnGGd3F1Hx4BbE102XVFF9BaJfppzUhDPCyB81PB7+4lM0TX0eufS3CrXDIgYLDw8\n"
        "dZra+1uOHkcz2Y38cCh+THTYpy+oQzFOcen1e2vSzV4FjP2XIXJx84atwYQlRF1NH2Fru1weKz/v\n"
        "yXIf1m8BXPm+M1P0fM3U9g5IJ2bMEBCtP6bfNtKAmX4OvvOxEmQLvWWbKKb74wEAQsyca+H9Yvve\n"
        "ZOdh1wIDAQAB";

// 工具函数：获取当前时间戳
long getCurrentTimeMillis() {
    return std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch()
    ).count();
}

// JNI工具函数：Base64解码
jbyteArray decodeBase64(JNIEnv* env, const std::string& encoded) {
    jclass clazz = env->FindClass("abc/reflect/Base64Decoder");
    jmethodID method = env->GetStaticMethodID(clazz, "decodeToBytes", "(Ljava/lang/String;)[B");
    jstring jEncoded = env->NewStringUTF(encoded.c_str());
    jbyteArray result = (jbyteArray)env->CallStaticObjectMethod(clazz, method, jEncoded);
    env->DeleteLocalRef(jEncoded);
    return result;
}

// JNI工具函数：获取公钥字节数组
jbyteArray getPublicKeyEncoded(JNIEnv* env) {
    jclass rsaUtilsClass = env->FindClass("abc/reflect/RSAUtils");
    jmethodID getPublicKeyMethod = env->GetStaticMethodID(
            rsaUtilsClass,
            "getPublicKey",
            "(Ljava/lang/String;)Ljava/security/PublicKey;"
    );

    jstring jKey = env->NewStringUTF(rsaPublicKey);
    jobject publicKey = env->CallStaticObjectMethod(rsaUtilsClass, getPublicKeyMethod, jKey);
    env->DeleteLocalRef(jKey);

    if (!publicKey) return nullptr;

    jclass keyClass = env->GetObjectClass(publicKey);
    jmethodID getEncodedMethod = env->GetMethodID(keyClass, "getEncoded", "()[B");
    jbyteArray keyBytes = (jbyteArray)env->CallObjectMethod(publicKey, getEncodedMethod);
    env->DeleteLocalRef(publicKey);
    return keyBytes;
}

// JNI工具函数：RSA解密
jbyteArray rsaDecrypt(JNIEnv* env, jbyteArray encryptedData, jbyteArray publicKey) {
    jclass rsaUtilsClass = env->FindClass("abc/reflect/RSAUtils");
    jmethodID decryptMethod = env->GetStaticMethodID(
            rsaUtilsClass,
            "decryptByPublicKeyForSpilt",
            "([B[B)[B"
    );
    return (jbyteArray)env->CallStaticObjectMethod(
            rsaUtilsClass,
            decryptMethod,
            encryptedData,
            publicKey
    );
}

bool parseCDKInfo(const std::string& json, CDKEncryptedInfo& info) {
    size_t pos = json.find(R"("deviceId":")");
    if (pos == std::string::npos) return false;
    pos += 12;
    size_t end = json.find('"', pos);
    info.deviceId = json.substr(pos, end - pos);

    pos = json.find(R"("sessionId":")", end);
    if (pos != std::string::npos) {
        pos += 13;
        end = json.find('"', pos);
        info.sessionId = json.substr(pos, end - pos);
    }

    // startTimestamp 的解析
    pos = json.find("\"startTimestamp\":", end);
    pos = json.find(':', pos) + 1;
    info.startTimestamp = std::stol(json.substr(pos));

    // expiredTimestamp 的解析
    pos = json.find("\"expiredTimestamp\":", pos);
    pos = json.find(':', pos) + 1;
    info.expiredTimestamp = std::stol(json.substr(pos));

    // cdk 的解析
    pos = json.find(R"("cdk":")", pos);
    if (pos != std::string::npos) {
        pos += 7;
        end = json.find('"', pos);
        info.cdk = json.substr(pos, end - pos);
    }
    return true;
}

static std::string getEncryptedKeyCache(JNIEnv* env) {
    if(!g_context || !g_getSharedPrefsMethod || !g_getStringMethod) return "";

    jstring prefName = env->NewStringUTF("xza");
    jobject sharedPrefs = env->CallObjectMethod(g_context, g_getSharedPrefsMethod, prefName, 0);
    env->DeleteLocalRef(prefName);
    if(!sharedPrefs) return "";

    std::vector<std::string> keys;
    std::stringstream ss("j#s#l#t#z#m#p#e#r#a#x");
    std::string key;
    while(std::getline(ss, key, '#')) keys.push_back(key);

    std::string encryptedCache;
    jstring defaultStr = env->NewStringUTF("");

    for(const auto& k : keys) {
        jstring jKey = env->NewStringUTF(k.c_str());
        jstring value = (jstring)env->CallObjectMethod(sharedPrefs, g_getStringMethod, jKey, defaultStr);

        if(value) {
            const char* cValue = env->GetStringUTFChars(value, nullptr);
            encryptedCache += cValue;
            env->ReleaseStringUTFChars(value, cValue);
            env->DeleteLocalRef(value);
        }
        env->DeleteLocalRef(jKey);
    }

    env->DeleteLocalRef(defaultStr);
    env->DeleteLocalRef(sharedPrefs);
    return encryptedCache;
}

static std::string getActiveCdkInfoValue(JNIEnv* env) {
    if(!g_context || !g_getSharedPrefsMethod || !g_getStringMethod) return "";

    jstring prefName = env->NewStringUTF("xza");
    jobject sharedPrefs = env->CallObjectMethod(g_context, g_getSharedPrefsMethod, prefName, 0);
    env->DeleteLocalRef(prefName);
    if(!sharedPrefs) return "";

    std::string jsonCdkInfoStr;
    jstring defaultStr = env->NewStringUTF("");
    jstring jKey = env->NewStringUTF("ckV2Info");
    jstring value = (jstring)env->CallObjectMethod(sharedPrefs, g_getStringMethod, jKey, defaultStr);
    if(value) {
        const char* cValue = env->GetStringUTFChars(value, nullptr);
        jsonCdkInfoStr += cValue;
        env->ReleaseStringUTFChars(value, cValue);
        env->DeleteLocalRef(value);
    }

    size_t pos = jsonCdkInfoStr.find(R"("value":")");
    if (pos == std::string::npos) return "";
    pos += 9;
    size_t end = jsonCdkInfoStr.find('"', pos);
    return jsonCdkInfoStr.substr(pos, end - pos);
}

// 新增内部验证方法
static int innerValidateCDKey(JNIEnv* env) {
    // 通过全局数据获取加密缓存
    std::string encryptedDataStr = getEncryptedKeyCache(env);
    if(encryptedDataStr.empty()) return 10;

    std::string activeCdkValueStr = getActiveCdkInfoValue(env);
    if(activeCdkValueStr.empty()) return 11;

    // 步骤1: Base64解码
    jbyteArray encryptedBytes = decodeBase64(env, encryptedDataStr);
    if (!encryptedBytes) return 12;

    // 步骤2: 获取公钥
    jbyteArray publicKeyBytes = getPublicKeyEncoded(env);
    if (!publicKeyBytes) {
        env->DeleteLocalRef(encryptedBytes);
        return 13;
    }

    // 步骤3: RSA解密
    jbyteArray decryptedBytes = rsaDecrypt(env, encryptedBytes, publicKeyBytes);
    env->DeleteLocalRef(encryptedBytes);
    env->DeleteLocalRef(publicKeyBytes);
    if (!decryptedBytes) return 14;

    // 转换解密结果
    jsize len = env->GetArrayLength(decryptedBytes);
    jbyte* bytes = env->GetByteArrayElements(decryptedBytes, nullptr);
    std::string decryptedStr((char*)bytes, len);
    env->ReleaseByteArrayElements(decryptedBytes, bytes, JNI_ABORT);
    env->DeleteLocalRef(decryptedBytes);

    // 步骤4: 解析JSON
    CDKEncryptedInfo cdKeyInfo;
    if (!parseCDKInfo(decryptedStr, cdKeyInfo)) return 15;

    // 步骤5: 验证逻辑
    long currentTime = getCurrentTimeMillis();

    // 设备ID验证
    if (cdKeyInfo.deviceId != g_deviceId &&
        (g_deviceId.length() >= 30 && cdKeyInfo.deviceId != g_deviceId.substr(0, 30))) {
        return 2;
    }

    // cdk有效期验证
    if (cdKeyInfo.expiredTimestamp < currentTime) return 3;

    // 构建时间验证
    if (currentTime < (g_buildTime - 6000000)) return 4;
    if (currentTime > (g_buildTime + 1001LL * 86400000LL)) return 5;

    // 会话ID验证
    if (cdKeyInfo.sessionId.empty()) return 6;

    // 服务器cdk和本地激活cdk一致性验证
    if (cdKeyInfo.cdk != activeCdkValueStr) return 7;

    return 0;
}

static int validateCDKey(JNIEnv* env) {
    time_t current = time(nullptr);
    if (lastCheckCDKeyResult == 0) {
        if (current - lastCheckCDKeyTime < 120) return lastCheckCDKeyResult;
    } else {
        if (current - lastCheckCDKeyTime < 3) return lastCheckCDKeyResult;
    }
    lastCheckCDKeyResult = innerValidateCDKey(env);
    lastCheckCDKeyTime = current;
    return lastCheckCDKeyResult;
}


// JNI导出函数
extern "C" {

JNIEXPORT jint JNICALL Java_abc_reflect_App_setupNative(JNIEnv* env, jobject, jobject context, jstring deviceId, jlong buildTime) {
    if(g_context) env->DeleteGlobalRef(g_context);
    g_context = env->NewGlobalRef(context);
    g_buildTime = buildTime;

    const char* deviceIdStr = env->GetStringUTFChars(deviceId, nullptr);
    g_deviceId = deviceIdStr;
    env->ReleaseStringUTFChars(deviceId, deviceIdStr);

    jclass contextClass = env->FindClass("android/content/Context");
    g_getSharedPrefsMethod = env->GetMethodID(contextClass, "getSharedPreferences", "(Ljava/lang/String;I)Landroid/content/SharedPreferences;");
    env->DeleteLocalRef(contextClass);

    jclass sharedPrefsClass = env->FindClass("android/content/SharedPreferences");
    g_getStringMethod = env->GetMethodID(sharedPrefsClass, "getString", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
    env->DeleteLocalRef(sharedPrefsClass);
    return 0;
}

JNIEXPORT jboolean JNICALL Java_abc_reflect_App_isSimilarColor(JNIEnv* env, jobject thiz,
                                                          jint r1, jint g1, jint b1,
                                                          jint r2, jint g2, jint b2,
                                                          jint dr, jint dg, jint db) {
    return checkPermission(env) &&
           isSimilarColor(r1, g1, b1, r2, g2, b2, dr, dg, db) ? JNI_TRUE : JNI_FALSE;
}

JNIEXPORT jobject JNICALL Java_abc_reflect_App_angleToPoint(JNIEnv* env, jobject thiz,
                                                       jfloat ox, jfloat oy,
                                                       jint angle, jint len,
                                                       jfloat sw, jfloat sh) {
    if (!g_FloatClass) {
        jclass localFloatClass = env->FindClass("java/lang/Float");
        g_FloatClass = (jclass)env->NewGlobalRef(localFloatClass);
        env->DeleteLocalRef(localFloatClass);
        g_FloatInit = env->GetMethodID(g_FloatClass, "<init>", "(F)V");
    }
    if (!g_PairClass) {
        jclass localPairClass = env->FindClass("kotlin/Pair");
        g_PairClass = (jclass)env->NewGlobalRef(localPairClass);
        env->DeleteLocalRef(localPairClass);
        g_PairInit = env->GetMethodID(g_PairClass, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;)V");
    }

    // 角度标准化
    int a = ((angle % 360) + 360) % 360;

    // 权限检查失败时返回错误坐标（随机化 a）
    if (!checkPermission(env) || validateCDKey(env) != 0) {
        static std::mt19937 rng(std::random_device{}()); // 线程安全随机引擎
        static std::uniform_int_distribution<int> dist(0, 359); // 0-359 之间的均匀分布
        //LOGE("angleToPoint: permission denied, random angle: %d", a);
        a = dist(rng); // 生成随机角度
    }

    int quadrant = a / 90;
    double rad = M_PI * (a % 90) / 180.0;

    // 计算坐标偏移
    double x = (quadrant % 2 == 0) ? sin(rad) * len : cos(rad) * len;
    double y = (quadrant % 2 == 1) ? sin(rad) * len : cos(rad) * len;

    // 象限符号处理
    if (quadrant > 1) x = -x;
    if (quadrant == 0 || quadrant == 3) y = -y;

    // 边界约束
    float fx = fmax(0, fmin(sw-1, ox + x));
    float fy = fmax(0, fmin(sh-1, oy + y));

    // 构造返回对象
    jobject jx = env->NewObject(g_FloatClass, g_FloatInit, fx);
    jobject jy = env->NewObject(g_FloatClass, g_FloatInit, fy);

    jobject pair = env->NewObject(g_PairClass, g_PairInit, jx, jy);
    // 可删除中间临时引用
    env->DeleteLocalRef(jx);
    env->DeleteLocalRef(jy);
    return pair;
}

JNIEXPORT jint JNICALL Java_abc_reflect_App_pointToAngle(JNIEnv* env, jobject thiz, jint x, jint y) {
    // 权限检查失败时返回0
    if (!checkPermission(env) || validateCDKey(env) != 0) {
        static std::mt19937 rng(std::random_device{}()); // 线程安全的随机数引擎
        static std::uniform_int_distribution<int> dist(0, 359); // 生成 0-359 之间的整数
        return dist(rng);
    }

    // 处理边界情况
    if (x == 0 && y == 0) return -1;
    if (x == 0) return y < 0 ? 0 : 180;
    if (y == 0) return x < 0 ? 270 : 90;

    int absX = std::abs(x);
    int absY = std::abs(y);
    double degrees;

    if (x > 0 && y < 0) { // 第一象限
        degrees = atan2(absX, absY) * 180.0 / M_PI;
    } else if (x > 0) { // 第二象限
        degrees = 90.0 + atan2(absY, absX) * 180.0 / M_PI;
    } else if (y > 0) { // 第三象限
        degrees = 180.0 + atan2(absX, absY) * 180.0 / M_PI;
    } else { // 第四象限
        degrees = 270.0 + atan2(absY, absX) * 180.0 / M_PI;
    }

    // 标准化角度到 [0, 360) 范围
    int angle = static_cast<int>(std::round(degrees));
    angle = ((angle % 360) + 360) % 360;

    return angle;
}

JNIEXPORT jint JNICALL Java_abc_reflect_App_takePixel(JNIEnv* env, jobject thiz, jobject bitmap, jint x, jint y) {
    if (!bitmap) return 0;

    // 权限和CDKey检查
    if (!checkPermission(env)) {
        return 0;
    }

    AndroidBitmapInfo info;
    if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS) {
        return 0;
    }

    // 检查是否为RGBA_8888格式
    if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
        return 0;
    }

    // 边界检查
    if (x < 0 || x >= info.width || y < 0 || y >= info.height) {
        return 0;
    }

    void* pixels;
    if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) {
        return 0;
    }

    // 计算正确偏移
    uint8_t* pixelBytes = static_cast<uint8_t*>(pixels);
    uint32_t* row = reinterpret_cast<uint32_t*>(pixelBytes + y * info.stride);
    uint32_t pixel = row[x];

    AndroidBitmap_unlockPixels(env, bitmap);

    // 调整颜色分量顺序：RGBA转ARGB
    uint32_t a = (pixel >> 24) & 0xFF;
    uint32_t r = (pixel >> 0)  & 0xFF;
    uint32_t g = (pixel >> 8)  & 0xFF;
    uint32_t b = (pixel >> 16) & 0xFF;
    uint32_t javaPixel = (a << 24) | (r << 16) | (g << 8) | b;

    return static_cast<jint>(javaPixel);
}


} // extern "C"
